﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using UtilZ.Dotnet.Ex.TTLV;

namespace UtilZ.Dotnet.Ex.Config
{
    /// <summary>
    /// 配置枚举值转换器
    /// </summary>
    public class ConfigEnumValueConverter : IConfigValueConverter
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        public ConfigEnumValueConverter()
        {

        }


        private EnumConverter _converter = null;
        private EnumConverter GetEnumConverter(Type enumType)
        {
            if (this._converter == null)
            {
                lock (this)
                {
                    if (this._converter == null)
                    {
                        this._converter = new EnumConverter(enumType);
                    }
                }
            }

            return this._converter;
        }

        /// <summary>
        /// 将属性值转换为字符串
        /// </summary>
        /// <param name="propertyInfo">PropertyInfo</param>
        /// <param name="value">属性值</param>
        /// <returns>字符串</returns>
        public string ConvertTo(PropertyInfo propertyInfo, object value)
        {
            return (string)this.GetEnumConverter(propertyInfo.PropertyType).ConvertTo(value, typeof(string));
        }

        /// <summary>
        /// 将字符串转换为属性值
        /// </summary>
        /// <param name="propertyInfo">PropertyInfo</param>
        /// <param name="value">字符串</param>
        /// <returns>属性值</returns>
        public object ConvertFrom(PropertyInfo propertyInfo, string value)
        {
            return this.GetEnumConverter(propertyInfo.PropertyType).ConvertFrom(value);
        }

    }

    /// <summary>
    /// 配置值转换器工厂接口
    /// </summary>
    public interface IConfigValueConverterFactory
    {
        /// <summary>
        /// 创建配置值转换器
        /// </summary>
        /// <param name="propertyInfo">需要转换器的属性</param>
        /// <returns>配置值转换器</returns>
        IConfigValueConverter Create(PropertyInfo propertyInfo);
    }

    /// <summary>
    /// 配置值转换接口
    /// </summary>
    public interface IConfigValueConverter
    {
        /// <summary>
        /// 将属性值转换为字符串
        /// </summary>
        /// <param name="propertyInfo">PropertyInfo</param>
        /// <param name="value">属性值</param>
        /// <returns>字符串</returns>
        string ConvertTo(PropertyInfo propertyInfo, object value);

        /// <summary>
        /// 将字符串转换为属性值
        /// </summary>
        /// <param name="propertyInfo">PropertyInfo</param>
        /// <param name="value">字符串</param>
        /// <returns>属性值</returns>
        object ConvertFrom(PropertyInfo propertyInfo, string value);
    }
}
